﻿using Fleck;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using System.Runtime.InteropServices;
using System.Collections.Concurrent;
using static Yb.PrintPlug;
using static Jx.ListView;
using Yb;
using System.Threading;
using System.Net.Sockets;
using System.Reflection;
using System.Resources;
namespace YbPrintPlug
{
    public partial class Form1 : Form
    {
        private Yb.Mqtt mqtt = null;
        private YbLog log = new YbLog("logs");
        public class ScreenInfo
        {
            // 🔹 1. 像素尺寸（分辨率）
            public int PixelWidth { get; set; }
            public int PixelHeight { get; set; }

            // 🔹 2. 物理尺寸（真实硬件尺寸）
            public double PhysicalWidthMM { get; set; }
            public double PhysicalHeightMM { get; set; }
            public double PhysicalWidthInches => PhysicalWidthMM / 25.4;
            public double PhysicalHeightInches => PhysicalHeightMM / 25.4;
            public double DiagonalInches => Math.Sqrt(PhysicalWidthInches * PhysicalWidthInches + PhysicalHeightInches * PhysicalHeightInches);

            // 🔹 3. Windows 缩放比例
            public double ScaleFactor { get; set; }
            public string ScalePercentage => $"{(ScaleFactor * 100):F0}%";

            // 🔹 4. 每毫米多少像素（真实物理密度）
            public double PixelsPerMillimeterX { get; set; }
            public double PixelsPerMillimeterY { get; set; }
            public Dictionary<string, SizeF> Screens;

            // 🔹 数据来源
            public string Source { get; set; } // "WMI", "Fallback"
            public List<string> FontList { get; set; }

            // 🔹 可读字符串（调试用）
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this, Formatting.Indented);
            }
        }
        public static class MonitorInfo
        {
            [StructLayout(LayoutKind.Sequential, Pack = 1)]
            public struct EdidStruct
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
                public byte[] Data;
            }

            public static (double widthMm, double heightMm)? GetPhysicalSizeFromEdid()
            {
                try
                {
                    using (var searcher = new ManagementObjectSearcher("root\\wmi", "SELECT * FROM WmiMonitorID"))
                    using (var results = searcher.Get())
                    {
                        foreach (ManagementObject result in results)
                        {
                            var edid = (byte[])result["EDID"];
                            if (edid?.Length >= 128)
                            {
                                // EDID 中物理尺寸位于偏移 0x15（字节）
                                byte b = edid[0x15];

                                int widthCm = (b & 0xF0) >> 4;
                                int heightCm = (b & 0x0F);

                                // 如果值为 0，表示未指定（常见于虚拟机）
                                if (widthCm == 0 || heightCm == 0) continue;

                                return (widthCm * 10.0, heightCm * 10.0); // cm → mm
                            }
                        }
                    }
                }
                catch { }

                return null;
            }
        }
        private NotifyIcon notifyIcon;
        private ContextMenuStrip contextMenu;
        private void SetupNotifyIcon()
        {
            // 创建右键菜单
            contextMenu = new ContextMenuStrip();

            // 添加"显示窗口"菜单项
            var showItem = new ToolStripMenuItem("显示窗口");
            showItem.Click += (s, e) =>
            {
                Show();
                WindowState = FormWindowState.Normal;
                ShowInTaskbar = true;
                Activate();
            };
            contextMenu.Items.Add(showItem);

            // 添加分隔线
            contextMenu.Items.Add(new ToolStripSeparator());

            var exitItem = new ToolStripMenuItem("退出");
            exitItem.Click += (s, e) => Application.Exit();
            contextMenu.Items.Add(exitItem);

            // 使用窗口自身的图标
            notifyIcon = new NotifyIcon
            {
                Icon = this.Icon,
                Text = this.Text,
                ContextMenuStrip = contextMenu,
                Visible = true
            };

            // 双击：显示窗口
            notifyIcon.MouseClick += (s, e) =>  // 🔥 注意这里应该是 DoubleClick 而不是 Click
            {
                if (e.Button == MouseButtons.Left)
                {
                    Show();
                    WindowState = FormWindowState.Normal;
                    ShowInTaskbar = true;
                    Activate();
                }
            };
        }
        [Serializable]
        private class LogInfo
        {
            public string CreateTime { get; set; }
            public string Kind { get; set; }
            public string Message { get; set; }
            public LogInfo(string kind, string message)
            {
                CreateTime = DateTime.Now.ToString();
                Kind = kind;
                Message = message;
            }
        }
        private void AddLog(string kind, string message)
        {
            if (log != null)
            {
                loglistview.Add(new LogInfo(kind, message));
                log.Log(kind, message);
            }
        }
        // 窗口最小化时自动隐藏（防止用户手动最小化后还看到任务栏图标）
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e); // 建议先调用 base

            if (WindowState == FormWindowState.Minimized)
            {
                // 最小化时隐藏窗体并从任务栏移除
                Hide();
                ShowInTaskbar = false;
                notifyIcon.ShowBalloonTip(1000, "提示", "打印组件已最小化到托盘", ToolTipIcon.Info);
            }
            else if (WindowState == FormWindowState.Normal || WindowState == FormWindowState.Maximized)
            {
                // 恢复或最大化时，确保在任务栏显示（但注意：此时窗体必须是 Visible = true 才有效）
                ShowInTaskbar = true;
                // 如果之前被 Hide() 了，这里可能需要 Show()，但通常窗口状态改变时会自动显示
            }
        }

        public static ScreenInfo GetPrimaryScreenInfo()
        {
            var screenInfo = new SystemInfo();
            var pnpIds = screenInfo.GetMonitorPnpDeviceId();

            // 只关心主显示器
            var primaryScreen = Screen.PrimaryScreen;
            if (primaryScreen == null) return null;

            var info = new ScreenInfo();
            info.FontList = Yb.PrintPlug.GetFontsThatNameContainsChinese();

            // 🔹 1. 获取真实的物理分辨率（不受缩放影响）
            DEVMODE devMode = new DEVMODE();
            devMode.dmSize = (ushort)Marshal.SizeOf(devMode);

            bool success = EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref devMode);
            if (success)
            {
                info.PixelWidth = devMode.dmPelsWidth;
                info.PixelHeight = devMode.dmPelsHeight;
            }
            else
            {
                // 备选方案：使用 WMI 获取物理分辨率
                info.PixelWidth = primaryScreen.Bounds.Width;
                info.PixelHeight = primaryScreen.Bounds.Height;
                // 注意：这个可能还是受缩放影响的
            }

            // 🔹 2. 获取物理尺寸（真实硬件尺寸）
            double physicalWidthCm = 0;
            double physicalHeightCm = 0;
            bool hasPhysicalSize = false;
            info.Screens = new Dictionary<string, SizeF>();
            // 查找主显示器对应的物理尺寸
            foreach (var pnpId in pnpIds)
            {
                var size = screenInfo.GetMonitorPhysicalSize(pnpId);
                if (size != null)
                {
                    if (physicalWidthCm == 0 && size.Width != 0)
                    {
                        physicalWidthCm = size.Width;
                        physicalHeightCm = size.Height;
                        hasPhysicalSize = true;
                    }
                    if (!info.Screens.ContainsKey(pnpId))
                    {
                        info.Screens.Add(pnpId, size);
                    }
                }
            }

            // 如果无法获取物理尺寸，使用备选方法
            if (!hasPhysicalSize)
            {
                var edidSize = MonitorInfo.GetPhysicalSizeFromEdid();
                if (edidSize != null)
                {
                    info.PhysicalWidthMM = edidSize.Value.widthMm;
                    info.PhysicalHeightMM = edidSize.Value.heightMm;
                    info.Source = "EDID Fallback";
                }
                else
                {
                    info.PhysicalWidthMM = 0;
                    info.PhysicalHeightMM = 0;
                    info.Source = "No Physical Size Available";
                    return info;
                }
            }
            else
            {
                info.PhysicalWidthMM = Math.Round(physicalWidthCm * 10, 2);
                info.PhysicalHeightMM = Math.Round(physicalHeightCm * 10, 2);
                info.Source = "Direct Physical Size (SystemInfo)";
            }

            // 🔹 3. 计算每毫米多少像素（真实物理密度）
            if (info.PhysicalWidthMM > 0 && info.PhysicalHeightMM > 0)
            {
                info.PixelsPerMillimeterX = Math.Round(info.PixelWidth / info.PhysicalWidthMM, 8);
                info.PixelsPerMillimeterY = Math.Round(info.PixelHeight / info.PhysicalHeightMM, 8);
            }
            else
            {
                info.PixelsPerMillimeterX = 0;
                info.PixelsPerMillimeterY = 0;
            }

            // 🔹 4. 计算 Windows 缩放比例
            using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
            {
                float dpiX = graphics.DpiX;
                info.ScaleFactor = Math.Round(dpiX / 96.0, 2);
            }

            return info;
        }

        // 需要添加的 Windows API 相关定义
        [DllImport("user32.dll")]
        static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);

        const int ENUM_CURRENT_SETTINGS = -1;

        [StructLayout(LayoutKind.Sequential)]
        public struct DEVMODE
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string dmDeviceName;
            public ushort dmSpecVersion;
            public ushort dmDriverVersion;
            public ushort dmSize;
            public ushort dmDriverExtra;
            public uint dmFields;
            public int dmPositionX;
            public int dmPositionY;
            public uint dmDisplayOrientation;
            public uint dmDisplayFixedOutput;
            public short dmColor;
            public short dmDuplex;
            public short dmYResolution;
            public short dmTTOption;
            public short dmCollate;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
            public string dmFormName;
            public ushort dmLogPixels;
            public uint dmBitsPerPel;
            public int dmPelsWidth;
            public int dmPelsHeight;
            public uint dmDisplayFlags;
            public uint dmDisplayFrequency;
            public uint dmICMMethod;
            public uint dmICMIntent;
            public uint dmMediaType;
            public uint dmDitherType;
            public uint dmReserved1;
            public uint dmReserved2;
            public uint dmPanningWidth;
            public uint dmPanningHeight;
        }
        [Serializable]
        public class Message
        {
            public string Command { get; set; }
            public string Data { get; set; }
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this, Formatting.Indented);
            }
        }
        [Serializable]
        public class PrintDocInfo
        {
            public string TaskId { get; set; }
            public string CreateTime { get; set; }
            public string Form { get; set; }
            public string Data { get; set; }
            public string Static { get; set; }
        }
        private ConcurrentDictionary<string, Jx.ListView> printermap = new ConcurrentDictionary<string, Jx.ListView>();
        private Config mainconfig = null;
        public class QualityOption
        {
            public string DisplayName { get; set; }  // 显示给用户的文本
            public string Value { get; set; }        // 实际使用的值（如 "photo"）
        }
        private string thismcode = "";
        private bool _updatingUI = false;

        public Form1()
        {
            InitializeComponent();
            string mcode = Yb.WindowsInfo.GetMachineId();
            thismcode = mcode;
            mqtt = new Mqtt("60.247.147.167", 9001, "yb", "yellbuy", mcode);
            mqtt.OnOpen += Mqtt_OnOpen;
            mqtt.OnMessage += Mqtt_OnMessage;
            mqtt.ConnectAsync();
            mqtt.OnStateChange += (e) =>
            {
                if (statusStrip.InvokeRequired)
                {
                    // 当前不在 UI 线程，需要委托过去
                    statusStrip.Invoke(new Action(() =>
                    {
                        if (e)
                        {
                            iscloud.Image = global::YbPrintPlug.Properties.Resources.iscloud;
                            iscloud.Text = "云服务可用";
                        }
                        else
                        {
                            iscloud.Image = global::YbPrintPlug.Properties.Resources.notcloud;
                            iscloud.Text = "云服务不可用";
                        }
                    }));
                }
                else
                {
                    if (e)
                    {
                        iscloud.Image = global::YbPrintPlug.Properties.Resources.iscloud;
                        iscloud.Text = "云服务可用";
                    }
                    else
                    {
                        iscloud.Image = global::YbPrintPlug.Properties.Resources.notcloud;
                        iscloud.Text = "云服务不可用";
                    }
                }
            };
            Jx.ListView.Column logcolumn = new Jx.ListView.Column();
            logcolumn.Add("创建时间", "CreateTime", 200);
            logcolumn.Add("日志类型", "Kind", 100);
            logcolumn.Add("消息内容", "Message", 400);
            loglistview.BindColumn(logcolumn);

            var qualityOptions = new List<QualityOption>
            {
                new QualityOption { DisplayName = "草稿",       Value = "Draft" },
                new QualityOption { DisplayName = "标准",       Value = "Standard" },
                new QualityOption { DisplayName = "高质量",     Value = "Highquality" },
                new QualityOption { DisplayName = "照片级别",   Value = "Photo" }
            };
            printq.DataSource = qualityOptions;
            printq.DisplayMember = "DisplayName"; // 显示的字段
            printq.ValueMember = "Value";         // 实际值的字段
            // 确保 TabControl 填满整个窗体
            mainTab.Dock = DockStyle.Fill;

            Yb.Config config = new Yb.Config();
            mainconfig = config;
            ConfigBinding.Initialize(config);
            ConfigBinding.BindAll(tabPage1);

            var printerdata = Yb.PrintPlug.GetPrinterNames();

            for (int i = 0; i < printerdata.printers.Count; i++)
            {
                TabPage page = new TabPage();
                page.Text = printerdata.printers[i];

                // 👇 使用 TableLayoutPanel 垂直排列：第0行 = buttonGroup，第1行 = view
                TableLayoutPanel tableLayout = new TableLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    ColumnCount = 1, // 一列
                    RowCount = 2,    // 两行
                };

                // 第0行：固定高度 60
                tableLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60));
                // 第1行：填充剩余空间
                tableLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));

                // 控制按钮区域
                GroupBox buttonGroup = new GroupBox
                {
                    Text = "控制面板",
                    Dock = DockStyle.Fill, // 填满所在单元格
                };

                FlowLayoutPanel buttonPanel = new FlowLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    FlowDirection = FlowDirection.LeftToRight
                };

                Button btnSkip = new Button { Text = "继续", Width = 80 };
                Button btnCancel = new Button { Text = "取消", Width = 80 };

                buttonPanel.Controls.AddRange(new Control[] { btnSkip, btnCancel });
                buttonGroup.Controls.Add(buttonPanel);

                // 列表视图
                Jx.ListView view = new Jx.ListView
                {
                    Dock = DockStyle.Fill,
                    Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom,
                    BackColor = Color.White
                };

                // 设置列
                Jx.ListView.Column column = new Jx.ListView.Column();
                column.Add("打印任务", "TaskId", 240);
                column.Add("来源", "Form", 100);
                column.Add("创建时间", "CreateTime", 200);
                column.Add("状态", "Static", 100);
                view.BindColumn(column);
                view.SetPkField("TaskId");

                view.OnError += (string message) =>
                {
                    ShowErrMessage(message);
                };

                view.OnRun += async (obj) =>
                {
                    if (!(obj is PrintDocInfo pdata)) return (false, "数据类型不正确");
                    pdata.Static = "正在打印中...";
                    AddLog("打印", "开始打印文档[" + pdata.Form + "]" + pdata.TaskId);
                    var err = Yb.PrintPlug.Print(pdata.Data, config.Get<bool>("mainsetting.waitprinted", false));
                    if (err != null && err.code == 0)
                    {
                        pdata.Static = "打印成功";
                        AddLog("打印", "打印文档完成[" + pdata.Form + "]" + pdata.TaskId);
                        return (true, "");
                    }
                    else
                    {
                        AddLog("打印", "打印文档发生错误[" + pdata.Form + "]" + pdata.TaskId + ":" + err.message);
                        notifyIcon.ShowBalloonTip(1000, "打印错误", err.message, ToolTipIcon.Error);
                    }
                    pdata.Static = err.message;
                    return (false, err.message);
                };

                view.RunCursorList();

                // 👇 关键：把 buttonGroup 放到第0行，view 放到第1行
                tableLayout.Controls.Add(buttonGroup, 0, 0); // 列0，行0
                tableLayout.Controls.Add(view, 0, 1);        // 列0，行1

                page.Controls.Add(tableLayout);
                mainTab.Controls.Add(page);
                printermap.TryAdd(printerdata.printers[i], view);
            }
            websocket.OnBgen += (s) =>
            {
                AddLog("websocket", s);
            };
            websocket.OnStop += (s) =>
            {
                AddLog("websocket", s);
            };
            websocket.OnError += (s) =>
            {
                AddLog("websocket", s);
            };
            // WebSocket 消息处理
            websocket.Run += (message, socket) =>
            {
                try
                {
                    AddLog("WebSocket消息", $"{message}");
                    var command = JsonConvert.DeserializeObject<Message>(message);
                    if (command != null)
                    {
                        switch (command.Command)
                        {
                            case "getscreen":
                                AddLog("command", "执行获得屏幕信息");
                                var returnmessage = GetPrimaryScreenInfo();
                                socket.Send(returnmessage.ToString());
                                break;
                            case "getprintlist":
                                AddLog("command", "执行获得打印机列表");
                                var printinfo = Yb.PrintPlug.GetPrinterNames();
                                socket.Send(printinfo.ToString());
                                break;
                            case "print":
                                AddLog("command", "执行打印消息");
                                YbTemplate data = JsonConvert.DeserializeObject<YbTemplate>(command.Data);
                                if (string.IsNullOrEmpty(data.PrintName))
                                {
                                    notifyIcon.ShowBalloonTip(1000, "错误", "没有传递打印机名称，无法打印", ToolTipIcon.Error);
                                    return;
                                }
                                if (printermap.TryGetValue(data.PrintName, out Jx.ListView p))
                                {
                                    string taskid = data.TaskId;
                                    if (string.IsNullOrEmpty(taskid))
                                    {
                                        taskid = Guid.NewGuid().ToString();
                                    }
                                    p.Add(new PrintDocInfo
                                    {
                                        CreateTime = DateTime.Now.ToString(),
                                        TaskId = taskid,
                                        Form = "WebSocket",
                                        Data = command.Data,
                                        Static = "等待提交",
                                    });
                                }
                                else
                                {
                                    notifyIcon.ShowBalloonTip(1000, "错误", "没有找到打印机[" + data.PrintName + "]，如果是新增的打印机请重启软件后再使用", ToolTipIcon.Error);
                                    return;
                                }
                                if (config.Get<bool>("mainsetting.printmessage", true))
                                    notifyIcon.ShowBalloonTip(1000, "打印", "打印了一个文档", ToolTipIcon.Info);
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("执行错误: " + ex.Message + "\n" + ex.StackTrace, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            YbMessage errsocket = websocket.Init(config.Get<int>("mainsetting.port", 13526), config.Get<int>("mainsetting.wssport", 13527), AppDomain.CurrentDomain.BaseDirectory + "yb.pfx", "123456");
            if (errsocket.code == 0)
            {
                AddLog("websocket", errsocket.message);
            }
            Load += (s, e) =>
            {
                //this.ShowInTaskbar = false;
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                YbMessage err = Yb.PrintPlug.ActivateLicense();
                if (err != null)
                {
                    AddLog("版本", err.message);
                }
                
            };

            FormClosing += Form1_FormClosing;

            mainwebsocketport.ValueChanged += (s, e) =>
            {
                websocket.SetWsPort((int)mainwebsocketport.Value);
            };
            SetupNotifyIcon();
            AutoCheckUpdate();
        }
        private async void AutoCheckUpdate()
        {
            var updater = new AutoUpdater("http://www.ybxxjs.com/static/download/upgrade/qxprint/qx.json");
            YbMessage result = await updater.CheckAndShowUpdateDialogAsync();

            if (result != null)
            {
               AddLog("自动更新",result.message);
            }
        }
        private void Mqtt_OnMessage(string topic, byte[] payload)
        {
            // 将 byte[] 转为字符串（假设是 UTF-8 编码）
            string message = Encoding.UTF8.GetString(payload);

            AddLog("云消息", $"{message}");
            var command = JsonConvert.DeserializeObject<Message>(message);
            if (command != null)
            {
                switch (command.Command)
                {
                    case "print":
                        YbTemplate data = JsonConvert.DeserializeObject<YbTemplate>(command.Data);
                        if (string.IsNullOrEmpty(data.PrintName))
                        {
                            notifyIcon.ShowBalloonTip(1000, "错误", "没有传递打印机名称，无法打印", ToolTipIcon.Error);
                            return;
                        }
                        if (printermap.TryGetValue(data.PrintName, out Jx.ListView p))
                        {
                            string taskid = data.TaskId;
                            if (string.IsNullOrEmpty(taskid))
                            {
                                taskid = Guid.NewGuid().ToString();
                            }
                            p.Add(new PrintDocInfo
                            {
                                CreateTime = DateTime.Now.ToString(),
                                TaskId = taskid,
                                Form = "云打印",
                                Data = command.Data,
                                Static = "等待提交",
                            });
                        }
                        else
                        {
                            notifyIcon.ShowBalloonTip(1000, "错误", "没有找到打印机[" + data.PrintName + "]，如果是新增的打印机请重启软件后再使用", ToolTipIcon.Error);
                            return;
                        }
                        if (mainconfig.Get<bool>("mainsetting.printmessage", true))
                            notifyIcon.ShowBalloonTip(1000, "云打印", "打印了一个文档", ToolTipIcon.Info);
                        break;
                }
            }
        }
        private void Mqtt_OnOpen()
        {
            AddLog("云服务", "服务器链接成功");
            mqtt.SubscribeAsync($"printplug/{thismcode}", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
            mqtt.SendStringAsync("login", DateTime.Now.ToString() + "[" + thismcode + "]");
        }

        private void ShowErrMessage(string message)
        {
            this.Invoke(new Action(() =>
            {
                MessageBox.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }));
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // ⚠️ 只有在“真正要退出”时，才清理 NotifyIcon
            if (e.CloseReason != CloseReason.UserClosing) // 比如：Application.Exit()、系统关机等
            {
                if (notifyIcon != null)
                {
                    notifyIcon.Visible = false;
                    notifyIcon.Dispose();
                }
            }
            // 如果是用户点击关闭按钮，我们已经 Cancel 了，不要 dispose！
            base.OnFormClosing(e);
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果是用户点击了关闭按钮（非程序调用 Application.Exit()）
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true; // ❗ 取消关闭操作
                Hide();          // 隐藏窗口
                ShowInTaskbar = false; // 确保任务栏无残留
                                       // 可选：显示一个气泡提示
                notifyIcon.ShowBalloonTip(1000, "提示", "打印组件已最小化到托盘", ToolTipIcon.Info);
            }
            // 其他情况（如 Application.Exit()）允许关闭
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 注册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var about = new AboutWindow())
            {
                // 以模态方式显示（阻塞主窗口，直到关闭）
                about.ShowDialog(this); // 'this' 表示父窗口是当前 Form1
            }
        }
        private void OpenLogsFolder()
        {
            string logsPath = System.IO.Path.Combine(Application.StartupPath, "logs");

            if (System.IO.Directory.Exists(logsPath))
            {
                try
                {
                    var psi = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = logsPath,
                        UseShellExecute = true
                    };
                    System.Diagnostics.Process.Start(psi);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法打开日志目录：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("日志目录不存在，暂无日志文件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void 查看日志目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenLogsFolder();
        }

        private async void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var updater = new AutoUpdater("http://www.ybxxjs.com/static/download/upgrade/qxprint/qx.json");
            YbMessage result = await updater.CheckAndShowUpdateDialogAsync();

            if (result != null)
            {
                // 处理返回的消息
                if (result.code == 0)
                {
                    // 成功的情况
                    MessageBox.Show(result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // 失败的情况
                    MessageBox.Show(result.message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }
    }
}